package com.ittest.web.controller.system;

import com.github.pagehelper.PageInfo;
import com.ittest.domain.system.Permission;
import com.ittest.domain.system.Role;
import com.ittest.domain.system.User;
import com.ittest.service.system.RoleService;
import com.ittest.service.system.UserService;
import com.ittest.service.system.impl.RoleServiceImpl;
import com.ittest.service.system.impl.UserServiceImpl;
import com.ittest.utils.BeanUtil;
import com.ittest.web.controller.BaseServlet;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/system/user/*")
public class UserServlet extends BaseServlet {
    // 创建服务层对象
    private UserService userService = new UserServiceImpl();

    /**
     * 根据id修改密码
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    //点击修改按钮，实现页面密码的修改
    private void updatePwdById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取loginUser中的id
        String id = req.getParameter("id");
        //获取页面上输入的旧密码
        String pwd = req.getParameter("pwd");
        //获取页面上新加的密码
        String newPwd = req.getParameter("newPwd");
        //获取页面上的确认密码
        String affirmNewPwd = req.getParameter("affirmNewPwd");
        //获取存入到session中的loginUser中的密码
        User loginUser = (User)req.getSession().getAttribute("loginUser");
        String password = loginUser.getPassword();
        if (pwd != null && pwd.equals(password)) {
            //进行判断，新密码要和确认密码一致，不一致重新跳转到修改密码页面
            if (newPwd.equals(affirmNewPwd) && newPwd != null && affirmNewPwd != null && newPwd.length()>0 &&affirmNewPwd.length()>0) {
                //调用userService方法
                userService.updatePwdById(id, newPwd);
                //清除session中的loginUser
                req.getSession().removeAttribute("loginUser");
                //当数据修改完后，重定向登录页面
                resp.sendRedirect(req.getContextPath() + "/login.jsp");

            } else {
                req.getRequestDispatcher("/updatePassWord.jsp").forward(req, resp);
            }
        } else { //旧密码输入不正确时，进行提示，跳转修改页面
            req.getRequestDispatcher("/updatePassWord.jsp").forward(req, resp);
        }


    }

    /**
     * 自动登录
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void autoLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取session对象
        HttpSession session = req.getSession();
        //获取存入到session中的loginUser
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser != null) {
            //跳转页面
            req.getRequestDispatcher("/pages/home/main.jsp").forward(req, resp);
        } else {
            //重定向登录页面
            resp.sendRedirect(req.getContextPath() + "/login.jsp");
        }
    }

    /**
     * 根据用户名和密码登录
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取页面上的用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //记住登录的状态
        String ck = req.getParameter("ck");
        //调用userService层的login方法，将用户名和密码交给userService
        User user = userService.login(username, password);
        if (user != null) {
            //将登录者信息存入到session中
            req.getSession().setAttribute("loginUser", user);
            //实现记住用户名和密码
            Cookie cookieName = new Cookie("username", username);
            Cookie cookiePwd = new Cookie("pwd", password);
            //判断ck
            if ("1".equals(ck)) {//选择
                //设置时间
                cookieName.setMaxAge(60 * 60 * 24 * 365);
                cookiePwd.setMaxAge(60 * 60 * 24 * 365);
                //设置存储路径
                cookieName.setPath("/");
                cookiePwd.setPath("/");
            } else {
                //设置时间
                cookieName.setMaxAge(0);
                cookiePwd.setMaxAge(0);
                //设置存储路径
                cookieName.setPath("/");
                cookiePwd.setPath("/");
            }
            //发送客户端
            resp.addCookie(cookieName);
            resp.addCookie(cookiePwd);

            // 如果登录成功,加载该用户对应的角色对应的所有模块
            List<Permission> permissionList = userService.findPermissionById(user.getId());
            // 将数据传回前端页面
            req.setAttribute("permissionList",permissionList);

            //跳转页主页面
            req.getRequestDispatcher("/pages/home/main.jsp").forward(req, resp);
        } else {
            //登录不成功，先进行标记，跳转到登录页面
            /* req.setAttribute("www",0);*/
            resp.sendRedirect(req.getContextPath() + "/login.jsp");
        }
    }

    /**
     * 注销
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //清除session里数据
        //req.getSession().removeAttribute("loginUser");
        req.getSession().invalidate();
        //杀死cookie
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie : cookies) {
            if ("username".equals(cookie.getName()) || "pwd".equals(cookie.getName())) {
                cookie.setMaxAge(0);
                resp.addCookie(cookie);
            }
        }
        //跳回到登录页面
        resp.sendRedirect(req.getContextPath() + "/login.jsp");
    }


    

    // 分页查询
    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置分页数据
        int page = 1;
        int size = 10;
        // 判断从前端获取的数据
        if (StringUtils.isNotBlank(req.getParameter("page"))){
            page = Integer.parseInt(req.getParameter("page"));
        }
        if (StringUtils.isNotBlank(req.getParameter("size"))) {
            size = Integer.parseInt(req.getParameter("size"));
        }
        // 获取搜索框内容
        String sname = req.getParameter("sname");
        //调用userService层,查询数据
        List<User> list = userService.findAll(page, size, sname);
        // 设置分页插件
        PageInfo<User> pageInfo = new PageInfo<>(list);
        //数据存到request域中
        req.setAttribute("size",size);
        req.setAttribute("page",pageInfo);
        //跳转到页面
        req.getRequestDispatcher("/pages/system/user/user-list.jsp").forward(req,resp);
    }
    // 页面跳转
    protected void toAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/pages/system/user/user-add.jsp").forward(req,resp);
    }
    // 新增
    protected void save(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取前端传来的数据并封装
        User user = BeanUtil.fillBean(req, User.class);
        // 调用业务层方法
        userService.save(user);
        // 页面跳转
        req.getRequestDispatcher("/system/user/list").forward(req,resp);
    }
    // 批量删除
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取前端传来的id
        String id = req.getParameter("id");
        // 调用删除方法
        userService.delete(id);
        // 页面跳转
        req.getRequestDispatcher("/system/user/list").forward(req,resp);

    }
    // 页面跳转
    protected void toUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 查询所有的角色
        RoleService roleService = new RoleServiceImpl();
        List<Role> list = roleService.findAll();

        req.setAttribute("page",list);
        // 获取当前用户的id
        String id = req.getParameter("id");
        req.setAttribute("userId",id);
        // 调用方法查询用户对应的角色
        List<Role> roles = userService.findRoleByUserId(id);
        // 将数据添加到作用域
        req.setAttribute("page",roles);
        // 页面跳转
        req.getRequestDispatcher("/pages/system/user/user-role-add.jsp").forward(req,resp);
    }
    // 更改角色
    protected void addRoleToUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取用户的id
        String userId = req.getParameter("userId");
        // 获取对应的用户id
        String[] roleIds = req.getParameterValues("ids");
        // 调用业务层方法
        userService.addRoleToUser(userId,roleIds);
        // 页面跳转
        req.getRequestDispatcher("/system/user/list").forward(req,resp);
    }
    // 显示详情
    protected void findById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取前端传来的id
        String id = req.getParameter("id");
        // 根据id查询
        User user = userService.findById(id);
        req.setAttribute("user",user);
        // 页面跳转
        req.getRequestDispatcher("/pages/system/user/user-show.jsp").forward(req,resp);
    }
    // 改变状态
    protected void change(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取前端传来的id
        String id = req.getParameter("id");
        Integer status =Integer.parseInt(req.getParameter("status")) ;

        // 判断status的状态
        if (1 == status){
            status=0;
        }else if (0 == status){
            status=1;
        }
        //修改方法
        userService.change(status,id);
        // 页面跳转
        req.getRequestDispatcher("/system/user/list").forward(req,resp);
    }
}
